package cn.jussi.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.jussi.mvcproject.utils.CookieUtils;

/**
 * 实现自动登入的拦截器
 * @author 范俊熙
 *基本思路：判断请求中是否有cookie：userKey， ssid，并判断 userKey 和 ssid 是否正确
 *			有关键cookie，跳转到 main.jsp页面， 同时把username的值放到session里(是否登入的标志)
 *			没有关键cookie，页面正常显示
 */
public class AotoLoginFilter extends HttpFilter {
	@Override
	protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)throws IOException, ServletException {
		Cookie[] cookies = req.getCookies();
		String username = null;
		String ssid = null;
		if(cookies != null && cookies.length >0) {
			for(Cookie c: cookies) {
				if(c.getName().equals("userKey")) {
					username = c.getValue();
				}
				if(c.getName().equals("ssid")) {
					ssid = c.getValue();
				}
			}
			if(username != null && ssid != null && ssid.equals(CookieUtils.md5Encrypt(username))) {	//ture:证明登入过，而且选择了记住我，自动登入
				HttpSession session = req.getSession();
				session.setAttribute("user", username);
				resp.sendRedirect(req.getContextPath()+"/main.jsp");
			}else {//恶意构造的cookie，放行，正常显示login.jsp页面
				chain.doFilter(req, resp);	
			}
		}else {//未登入过，放行，正常显示login.jsp页面
			chain.doFilter(req, resp);
		}	
	}
}
